package com.example.lanchat;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattServer;
import android.bluetooth.BluetoothGattServerCallback;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.le.AdvertiseCallback;
import android.bluetooth.le.AdvertiseData;
import android.bluetooth.le.AdvertiseSettings;
import android.bluetooth.le.BluetoothLeAdvertiser;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.ParcelUuid;
import android.util.Log;
import android.view.View;
import android.view.Menu;

import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.navigation.NavigationView;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.lifecycle.MutableLiveData;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;

import com.example.lanchat.databinding.ActivityMainBinding;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class MainActivity extends AppCompatActivity {

    private AppBarConfiguration mAppBarConfiguration;
    private ActivityMainBinding binding;
    public BluetoothAdapter bluetoothAdapter;
     BluetoothManager bluetoothManager;
    private boolean mScanning;
    private Handler handler;
    public List<BluetoothDevice> myBTDeviceList = new ArrayList<>();
    public MutableLiveData<List> myBTDeviceLiveData = new MutableLiveData<>();
    public MutableLiveData<String> myNotifyLiveData = new MutableLiveData<>();
    // Stops scanning after 10 seconds.
    private static final long SCAN_PERIOD = 10000;
    public Boolean isExist = false;
    public Boolean isMaster = true;
    public Boolean isTCPServer = true;
    private String bluetoothDeviceAddress;
    private BluetoothGatt bluetoothGatt;
    private int connectionState = STATE_DISCONNECTED;
    private final static String TAG = "tag";
    private static final int STATE_DISCONNECTED = 0;
    private static final int STATE_CONNECTING = 1;
    private static final int STATE_CONNECTED = 2;

    public final static String ACTION_GATT_CONNECTED =
            "com.example.bluetooth.le.ACTION_GATT_CONNECTED";
    public final static String ACTION_GATT_DISCONNECTED =
            "com.example.bluetooth.le.ACTION_GATT_DISCONNECTED";
    public final static String ACTION_GATT_SERVICES_DISCOVERED =
            "com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED";
    public final static String ACTION_DATA_AVAILABLE =
            "com.example.bluetooth.le.ACTION_DATA_AVAILABLE";
    public final static String EXTRA_DATA =
            "com.example.bluetooth.le.EXTRA_DATA";
    BluetoothGattCharacteristic BCFFF1, BCFFF2, BCFFF3;
    private static final int REQUEST_ENABLE_BT = 2;
    BluetoothDevice descriptDevice;
    TcpClient client;
    TcpServer server;
    NavController navController;
    public static Boolean isBluetooth=false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        handler = new Handler();
        setSupportActionBar(binding.appBarMain.toolbar);
        binding.appBarMain.fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
        DrawerLayout drawer = binding.drawerLayout;
        NavigationView navigationView = binding.navView;
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        mAppBarConfiguration = new AppBarConfiguration.Builder(
                R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow, R.id.nav_chat, R.id.nav_conn,R.id.nav_tcp)
                .setOpenableLayout(drawer)
                .build();
        navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
        NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
        NavigationUI.setupWithNavController(navigationView, navController);
        // Initializes Bluetooth adapter.
       bluetoothManager =
                (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        bluetoothAdapter = bluetoothManager.getAdapter();
        //bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        // Ensures Bluetooth is available on the device and it is enabled. If not,
        // displays a dialog requesting user permission to enable Bluetooth.
        if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
            System.out.println("BluetoothAdapter为空，需要开启蓝牙");
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                //return;
            }
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }
        boolean aa = isLocationOpen(this);
        System.out.println("isLocationOpen:" + aa);
    }

    //扫描
    public void myBLEScan(final boolean enable) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            //return;
        }

        boolean aa = isLocationOpen(this);
        System.out.println("isLocationOpen:" + aa);

        if (enable) {
            // Stops scanning after a pre-defined scan period.
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mScanning = false;

                    bluetoothAdapter.getBluetoothLeScanner().stopScan(scanCallback);
                    //bluetoothAdapter.stopLeScan(leScanCallback);
                }
            }, SCAN_PERIOD);

            mScanning = true;
            bluetoothAdapter.getBluetoothLeScanner().startScan(scanCallback);
            System.out.println("BluetoothLeScanner().startScan");
            //bluetoothAdapter.startLeScan(leScanCallback);
        } else {
            mScanning = false;
            bluetoothAdapter.getBluetoothLeScanner().stopScan(scanCallback);
            //bluetoothAdapter.stopLeScan(leScanCallback);
        }

    }

    private ScanCallback scanCallback = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);
            isExist = false;
            System.out.println("onScanResult::" + result.getDevice().getAddress() + "--isExist:"+isExist);
            //如果是新的address则添加到list
            for (BluetoothDevice d : myBTDeviceList) {
                if (d.getAddress().equals(result.getDevice().getAddress())) {
                    isExist = true;
                    System.out.println("onScanResult::" + result.getDevice().getAddress() + "--isExist:"+isExist);
                    break;
                }
            }
            if (!isExist) {
                myBTDeviceList.add(result.getDevice());
            }
            myBTDeviceLiveData.setValue(myBTDeviceList);
        }

        @Override
        public void onBatchScanResults(List<ScanResult> results) {
            super.onBatchScanResults(results);
            System.out.println("onBatchScanResults::" + results.size());
        }

        @Override
        public void onScanFailed(int errorCode) {
            super.onScanFailed(errorCode);
            System.out.println("onScanFailed::" + errorCode);
        }
    };

    // Device scan callback.（扫描回调）
    private BluetoothAdapter.LeScanCallback leScanCallback =
            new BluetoothAdapter.LeScanCallback() {
                @Override
                public void onLeScan(final BluetoothDevice device, int rssi,
                                     byte[] scanRecord) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //如果是新的address则添加到list
                            for (BluetoothDevice d : myBTDeviceList) {
                                if (d.getAddress().equals(device.getAddress())) {
                                    isExist = true;
                                    break;
                                }
                            }
//                            if (device.getName() != null & !isExist) {
//                                myBTDeviceList.add(device);
//                            }
//                            myBTDeviceLiveData.setValue(myBTDeviceList);
                        }
                    });
                }
            };

    public void connectWithIndex(int index) {
        //开始连接时 停止扫描
        myBLEScan(false);

        BluetoothDevice bluetoothDevice = myBTDeviceList.get(index);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            //return;
        }
        System.out.println("connectWithIndex:" + index);
        bluetoothGatt = bluetoothDevice.connectGatt(this, false, gattCallback);

    }

    // Various callback methods defined by the BLE API.
    private final BluetoothGattCallback gattCallback =
            new BluetoothGattCallback() {
                @Override
                public void onConnectionStateChange(BluetoothGatt gatt, int status,
                                                    int newState) {
                    if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                        // TODO: Consider calling
                        //    ActivityCompat#requestPermissions
                        // here to request the missing permissions, and then overriding
                        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                        //                                          int[] grantResults)
                        // to handle the case where the user grants the permission. See the documentation
                        // for ActivityCompat#requestPermissions for more details.
                        //return;
                    }
                    String intentAction;
                    if (newState == BluetoothProfile.STATE_CONNECTED) {
                        intentAction = ACTION_GATT_CONNECTED;
                        connectionState = STATE_CONNECTED;
                        // broadcastUpdate(intentAction);
                        Log.i("tag", "Connected to GATT server.");

                        Log.i("tag", "Attempting to start service discovery:" +
                                bluetoothGatt.discoverServices());
                        //扫描service服务
                        bluetoothGatt = gatt;
                        bluetoothGatt.discoverServices();

                    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                        intentAction = ACTION_GATT_DISCONNECTED;
                        connectionState = STATE_DISCONNECTED;
                        Log.i("tag", "Disconnected from GATT server.");
                        // broadcastUpdate(intentAction);
                    }
                }

                @Override
                // New services discovered
                public void onServicesDiscovered(BluetoothGatt gatt, int status) {
                    if (status == BluetoothGatt.GATT_SUCCESS) {
                        //  broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
                        Log.i("tag", "gatt是" + gatt.getServices());
                        for (BluetoothGattService service : gatt.getServices()) {
                            Log.i("tag", "service" + service.getUuid().toString());
                            if (service.getUuid().toString().contains("fff0")) {
                                for (BluetoothGattCharacteristic BC : service.getCharacteristics()) {
                                    Log.i("tag", "BC是" + BC.getUuid().toString());
                                    if (BC.getUuid().toString().contains("fff1")) {
                                        //读
                                        BCFFF1 = BC;
                                    }
                                    if (BC.getUuid().toString().contains("fff2")) {
                                        //写
                                        BCFFF2 = BC;
                                    }
                                    if (BC.getUuid().toString().contains("fff3")) {
                                        //读，写
                                        BCFFF3 = BC;
                                    }
                                }
                            } else {
                                Log.w("tag", "onServicesDiscovered received: " + status);
                            }
                        }
                    }
                }

                @Override
                public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
                    super.onCharacteristicChanged(gatt, characteristic);
                    myNotifyLiveData.postValue(characteristic.getStringValue(0));
                }

                @Override
                // Result of a characteristic read operation
                public void onCharacteristicRead(BluetoothGatt gatt,
                                                 BluetoothGattCharacteristic characteristic,
                                                 int status) {
                    if (status == BluetoothGatt.GATT_SUCCESS) {
                        //  broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
                    }
                }
            };

    //开通知
    public void myNotifySet(Boolean enable) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            //return;
        }
        boolean result = bluetoothGatt.setCharacteristicNotification(BCFFF1,enable);
        System.out.println("setCharacteristicNotification Result"+result);
        if (result){
            List <BluetoothGattDescriptor> descriptorList = BCFFF1.getDescriptors();
            if (descriptorList!=null&&descriptorList.size()>0){
                for (BluetoothGattDescriptor descriptor:descriptorList){
                    descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                    bluetoothGatt.writeDescriptor(descriptor);
                }
            }
        }
        //bluetoothGatt.setCharacteristicNotification(BCFFF1, enable);

    }
    public void sendNotifyMSG(String msg){
        BluetoothGattCharacteristic characteristic = bluetoothGattServer
                .getService(UUID.fromString("0000fff0-0000-1000-8000-00805f9b34fb"))
                .getCharacteristic(UUID.fromString("0000fff1-0000-1000-8000-00805f9b34fb"));
        characteristic.setValue(msg.getBytes(StandardCharsets.UTF_8));
        if (descriptDevice!=null){
            bluetoothGattServer.notifyCharacteristicChanged(descriptDevice,characteristic,false);
        }else {
            Log.w("tag", "主机没有订阅该通知");
        }
    }
    /**
     * Begin advertising over Bluetooth that this device is connectable
     * and supports the Current Time Service.
     */
    BluetoothLeAdvertiser mBluetoothLeAdvertiser;
    public void startAdvertising() {
        BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();
        mBluetoothLeAdvertiser = bluetoothAdapter.getBluetoothLeAdvertiser();
        if (mBluetoothLeAdvertiser == null) {
            Log.w("tag", "Failed to create advertiser");
            return;
        }

        AdvertiseSettings settings = new AdvertiseSettings.Builder()
                .setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_BALANCED)
                .setConnectable(true)
                .setTimeout(0)
                .setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_MEDIUM)
                .build();

        AdvertiseData data = new AdvertiseData.Builder()
                .setIncludeDeviceName(true)
                .setIncludeTxPowerLevel(false)
                .addServiceUuid(new ParcelUuid(UUID.fromString("0000fff0-0000-0000-0000-000000000000")))
                .build();

        mBluetoothLeAdvertiser
                .startAdvertising(settings, data, mAdvertiseCallback);
        setServer();
    }
    AdvertiseCallback mAdvertiseCallback = new AdvertiseCallback() {
        @Override
        public void onStartSuccess(AdvertiseSettings settingsInEffect) {
            super.onStartSuccess(settingsInEffect);
            Log.i("mytag","settingsInEffect是："+settingsInEffect.toString());
        }

        @Override
        public void onStartFailure(int errorCode) {
            super.onStartFailure(errorCode);
            Log.i("mytag","errorCode是："+errorCode);

        }
    };
    /**
     * Stop Bluetooth advertisements.
     */
    private void stopAdvertising() {
        if (mBluetoothLeAdvertiser == null) return;

        mBluetoothLeAdvertiser.stopAdvertising(mAdvertiseCallback);
    }

    //写入的文本
    public void mySendWithText(String msg) {
        BCFFF2.setValue(msg.getBytes(StandardCharsets.UTF_8));
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            //return;
        }
        bluetoothGatt.writeCharacteristic(BCFFF2);
    }

    BluetoothGattServer bluetoothGattServer;

    private void setServer() {
        Log.i("mytag", "setServer：");
        if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            Log.i("mytag", "setServer：RETURN");
            //return;
        }
        bluetoothGattServer = bluetoothManager.openGattServer(this, mGattServerCallback);
        BluetoothGattService service = new BluetoothGattService(UUID.fromString("0000fff0-0000-1000-8000-00805f9b34fb"), 0);
        BluetoothGattCharacteristic characteristic1 = new BluetoothGattCharacteristic(UUID.fromString("0000fff1-0000-1000-8000-00805f9b34fb"), BluetoothGattCharacteristic.PROPERTY_READ | BluetoothGattCharacteristic.PROPERTY_NOTIFY, BluetoothGattCharacteristic.PERMISSION_READ);
        BluetoothGattDescriptor descriptor1 = new BluetoothGattDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"), BluetoothGattDescriptor.PERMISSION_WRITE | BluetoothGattDescriptor.PERMISSION_READ);
        BluetoothGattDescriptor descriptor11 = new BluetoothGattDescriptor(UUID.fromString("00002901-0000-1000-8000-00805f9b34fb"), BluetoothGattDescriptor.PERMISSION_WRITE | BluetoothGattDescriptor.PERMISSION_READ);

        BluetoothGattCharacteristic characteristic2 = new BluetoothGattCharacteristic(UUID.fromString("0000fff2-0000-1000-8000-00805f9b34fb"), BluetoothGattCharacteristic.PROPERTY_WRITE, BluetoothGattCharacteristic.PERMISSION_WRITE);
        BluetoothGattDescriptor descriptor2 = new BluetoothGattDescriptor(UUID.fromString("00002901-0000-1000-8000-00805f9b34fb"), BluetoothGattDescriptor.PERMISSION_WRITE | BluetoothGattDescriptor.PERMISSION_READ);

        BluetoothGattCharacteristic characteristic3 = new BluetoothGattCharacteristic(UUID.fromString("0000fff3-0000-1000-8000-00805f9b34fb"), BluetoothGattCharacteristic.PROPERTY_READ | BluetoothGattCharacteristic.PROPERTY_WRITE | BluetoothGattCharacteristic.PROPERTY_NOTIFY, BluetoothGattCharacteristic.PERMISSION_WRITE);
        BluetoothGattDescriptor descriptor3 = new BluetoothGattDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"), BluetoothGattDescriptor.PERMISSION_WRITE | BluetoothGattDescriptor.PERMISSION_READ);
        BluetoothGattDescriptor descriptor31 = new BluetoothGattDescriptor(UUID.fromString("00002901-0000-1000-8000-00805f9b34fb"), BluetoothGattDescriptor.PERMISSION_WRITE | BluetoothGattDescriptor.PERMISSION_READ);

        characteristic1.addDescriptor(descriptor1);
        characteristic1.addDescriptor(descriptor11);
        service.addCharacteristic(characteristic1);

        characteristic2.addDescriptor(descriptor2);
        service.addCharacteristic(characteristic2);

        characteristic3.addDescriptor(descriptor3);
        characteristic3.addDescriptor(descriptor31);
        service.addCharacteristic(characteristic3);

        bluetoothGattServer.addService(service);

    }
    BluetoothGattServerCallback mGattServerCallback = new BluetoothGattServerCallback() {
        @Override
        public void onConnectionStateChange(BluetoothDevice device, int status, int newState) {
            super.onConnectionStateChange(device, status, newState);
            Log.i("mytag", "onConnectionStateChange：" + newState);
        }

        @Override
        public void onServiceAdded(int status, BluetoothGattService service) {
            super.onServiceAdded(status, service);
            Log.i("mytag", "onServiceAdded：" + service.getUuid().toString());
        }

        @Override
        public void onCharacteristicReadRequest(BluetoothDevice device, int requestId, int offset, BluetoothGattCharacteristic characteristic) {
            super.onCharacteristicReadRequest(device, requestId, offset, characteristic);
            Log.i("mytag", "onCharacteristicReadRequest：" + characteristic.getUuid().toString());
            if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                //return;
            }
            bluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, 0, TAG.getBytes(StandardCharsets.UTF_8));
        }

        @Override
        public void onCharacteristicWriteRequest(BluetoothDevice device, int requestId, BluetoothGattCharacteristic characteristic, boolean preparedWrite, boolean responseNeeded, int offset, byte[] value) {
            super.onCharacteristicWriteRequest(device, requestId, characteristic, preparedWrite, responseNeeded, offset, value);
            String str1 = new String(value);
            System.out.println("MyTag"+str1);
            myNotifyLiveData.postValue(str1);
            Log.i("mytag", "onCharacteristicWriteRequest：" + str1);
            if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                //return;
            }
            bluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, 0, TAG.getBytes(StandardCharsets.UTF_8));
        }

        @Override
        public void onDescriptorReadRequest(BluetoothDevice device, int requestId, int offset, BluetoothGattDescriptor descriptor) {
            super.onDescriptorReadRequest(device, requestId, offset, descriptor);
            Log.i("mytag", "onDescriptorReadRequest：" + descriptor);
            if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                //return;
            }
            bluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, 0, TAG.getBytes(StandardCharsets.UTF_8));
        }

        @Override
        public void onDescriptorWriteRequest(BluetoothDevice device, int requestId, BluetoothGattDescriptor descriptor, boolean preparedWrite, boolean responseNeeded, int offset, byte[] value) {
            super.onDescriptorWriteRequest(device, requestId, descriptor, preparedWrite, responseNeeded, offset, value);
            String str1 = new String(value);
            System.out.println("MyTag"+str1);
            Log.i("mytag", "onDescriptorWriteRequest：" + value);
            if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                //return;
            }

            descriptDevice=device;
            bluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, 0, TAG.getBytes(StandardCharsets.UTF_8));
        }

        @Override
        public void onExecuteWrite(BluetoothDevice device, int requestId, boolean execute) {
            super.onExecuteWrite(device, requestId, execute);
            Log.i("mytag", "onExecuteWrite：" + execute);
        }

        @Override
        public void onNotificationSent(BluetoothDevice device, int status) {
            super.onNotificationSent(device, status);
            Log.i("mytag", "onNotificationSent：" + status);
        }

        @Override
        public void onMtuChanged(BluetoothDevice device, int mtu) {
            super.onMtuChanged(device, mtu);
            Log.i("mytag", "onMtuChanged：" + mtu);
        }

        @Override
        public void onPhyUpdate(BluetoothDevice device, int txPhy, int rxPhy, int status) {
            super.onPhyUpdate(device, txPhy, rxPhy, status);
            Log.i("mytag", "onPhyUpdate：" + status);
        }

        @Override
        public void onPhyRead(BluetoothDevice device, int txPhy, int rxPhy, int status) {
            super.onPhyRead(device, txPhy, rxPhy, status);
            Log.i("mytag", "onPhyRead：" + status);
        }
    };
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
        return NavigationUI.navigateUp(navController, mAppBarConfiguration)
                || super.onSupportNavigateUp();
    }

    public static boolean isLocationOpen(final Context context){
        LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        //gps定位
        boolean isGpsProvider = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        //网络定位
        boolean isNetWorkProvider = manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        return isGpsProvider|| isNetWorkProvider;
    }
    public void startServer(){
        if (server==null){
            server=new TcpServer(myHandler);
        }
        server.startServer();
    }
    public void startClient(String ip){
        if (client==null){
            client=new TcpClient(myHandler);
        }
        try {
            client.startClient(ip);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    Handler myHandler=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg){
            switch (msg.what){
                case TcpServer.MSG_RECEIVE:
                    String s=(String) msg.obj;
                    if (s==null){
                        return;
                    }
                    myNotifyLiveData.postValue(s);
                case TcpServer.MSG_SEND:
                    break;
                case TcpServer.MSG_TCPCONN:
                    navController.navigate(R.id.nav_chat);
                    break;
                case TcpServer.MSG_TCPISCONN:
                    navController.navigate(R.id.nav_tcp);
                    break;
            }
            super.handleMessage(msg);
        }
    };
    public void sendTcpMSG(Boolean isServer,String msg){
        if (isServer){
            client.sendMSG(msg);
        }else {
            server.sendMSG(msg);
        }
    }
}